package com.core.image.tcp;

import com.core.image.core.Connector;
import com.core.image.core.IoContext;
import com.core.image.core.Packet;
import com.core.image.core.ReceivePacket;
import com.core.image.core.box.StringRecevicePacket;
import com.core.image.handler.ConnectorCloseChain;
import com.core.image.handler.ConnectorStringPacketChain;
import com.core.image.handler.DefaultNonConnectorStringPacketChain;
import com.core.image.handler.DefaultPrintConnectorCloseChain;
import com.core.image.utils.CloseUtils;
import com.core.image.utils.Foo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.nio.channels.SocketChannel;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/01/21
 */
public class ConnectorHandler extends Connector{
    private final File cachePath;
    private  final ConnectorCloseChain closeChain = new DefaultPrintConnectorCloseChain() ;
    private final ConnectorStringPacketChain stringPacketChain = new DefaultNonConnectorStringPacketChain();
    public ConnectorHandler(SocketChannel socketChannel,File cachePath)throws Exception{
        setup(socketChannel);
        this.cachePath = cachePath;
    }

    @Override
    protected File createNewReceiveFile(long length, byte[] headerInfo) {
        return  Foo.createRandomTemp(cachePath);
    }

    @Override
    public void onChannelClosed(SocketChannel channel) {
        super.onChannelClosed(channel);
        closeChain.handler(this,this);
        exit();
    }

    @Override
    protected  void  onReceivePacket(ReceivePacket packet){
        super.onReceivePacket(packet);
        switch (packet.type()){
            case Packet.TYPE_MEMORY_STRING:{
                deliveryStringPacket((StringRecevicePacket)packet);
                break;
            }
            default:{
                System.out.println("New Packet:" + packet.type() + "-" + packet.length());
            }
            }

}

    @Override
    public OutputStream createNewReceiveDirectOutputStream(long length, byte[] headerInfo) {
        return new ByteArrayOutputStream();
    }

    private void  deliveryStringPacket(StringRecevicePacket packet){
    IoContext.get().getScheduler().delivery(()->stringPacketChain.handler(this,packet));

}

    /**
     * 获取当前链接的消息处理责任链 链头
     * @return
     */
    public ConnectorStringPacketChain getStringPacketChain(){
        return stringPacketChain;
    }
    /**
     * 获取当前链接的关闭链接处理责任链 链头
     *
     * @return ConnectorCloseChain
     */
    public ConnectorCloseChain getCloseChain() {
        return closeChain;
    }
    @Override
    protected File createNewFile() {
        return null;
    }

    public void exit(){
       CloseUtils.close(this);

}
}
